﻿using System;

namespace Xenta.Utils
{
    /// <summary>
    /// Represents the enum helper.
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// Creates a mask for enum values.
        /// </summary>
        /// <typeparam name="TEnum">The enum type.</typeparam>
        /// <returns>The mask value.</returns>
        public static TEnum Mask<TEnum>()
            where TEnum : struct, IConvertible
        {
            var t = typeof(TEnum);
            if(!t.IsEnum)
                throw new ArgumentException();
            int mask = 0;
            foreach(var value in Enum.GetValues(t))
                mask |= Convert.ToInt32(value);
            return (TEnum)Enum.ToObject(t, mask);
        }

        /// <summary>
        /// Takes the AND operation on the enum value with specified mask.
        /// </summary>
        /// <typeparam name="TEnum">The enum type.</typeparam>
        /// <param name="value">The enum value.</param>
        /// <param name="mask">The mask.</param>
        /// <returns>The masked value.</returns>
        public static TEnum And<TEnum>(TEnum value, int mask)
            where TEnum : struct, IConvertible
        {
            var t = typeof(TEnum);
            if(!t.IsEnum)
                throw new ArgumentException();

            int intValue = Convert.ToInt32(value);
            int newValue = (intValue & mask);

            return (TEnum)Enum.ToObject(t, newValue);
        }
    }
}
